#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
配置管理模块
管理网站配置和系统配置
"""

import os
import yaml
import json
from pathlib import Path
from typing import Dict, Any, Optional

class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_dir: str = "config"):
        self.config_dir = Path(config_dir)
        self.config_dir.mkdir(exist_ok=True)
        
        self.sites_config_file = self.config_dir / "sites.yaml"
        self.system_config_file = self.config_dir / "system.yaml"
        
        self._ensure_config_files()
        
    def _ensure_config_files(self):
        """确保配置文件存在"""
        # 创建默认网站配置
        if not self.sites_config_file.exists():
            default_sites = {
                "example_site": {
                    "name": "示例网站",
                    "url": "https://example.com",
                    "login_required": False,
                    "login_url": "",
                    "username_selector": "",
                    "password_selector": "",
                    "submit_selector": "",
                    "content_selectors": {
                        "title": "h1, .title",
                        "content": ".content, .article-body",
                        "link": "a[href]",
                        "date": ".date, .publish-time"
                    },
                    "wait_after_login": 3,
                    "scroll_to_load": False,
                    "max_scroll_times": 3,
                    "enabled": False
                }
            }
            
            with open(self.sites_config_file, 'w', encoding='utf-8') as f:
                yaml.dump(default_sites, f, default_flow_style=False, allow_unicode=True)
                
        # 创建默认系统配置
        if not self.system_config_file.exists():
            default_system = {
                "schedule": {
                    "hour": "*/2",  # 每2小时执行一次
                    "minute": "0",
                    "second": "0"
                },
                "browser": {
                    "headless": True,
                    "window_size": [1920, 1080],
                    "user_agent": "",
                    "timeout": 30,
                    "implicit_wait": 10
                },
                "storage": {
                    "data_dir": "data",
                    "max_items_per_site": 1000,
                    "cleanup_days": 30
                }
            }
            
            with open(self.system_config_file, 'w', encoding='utf-8') as f:
                yaml.dump(default_system, f, default_flow_style=False, allow_unicode=True)
                
    def get_all_sites(self) -> Dict[str, Any]:
        """获取所有网站配置"""
        try:
            with open(self.sites_config_file, 'r', encoding='utf-8') as f:
                sites = yaml.safe_load(f) or {}
                
            # 只返回启用的网站
            return {name: config for name, config in sites.items() 
                   if config.get('enabled', False)}
        except Exception as e:
            print(f"读取网站配置失败: {e}")
            return {}
            
    def get_site_config(self, site_name: str) -> Optional[Dict[str, Any]]:
        """获取指定网站配置"""
        sites = self.get_all_sites()
        return sites.get(site_name)
        
    def add_site_config(self, site_name: str, config: Dict[str, Any]):
        """添加网站配置"""
        try:
            with open(self.sites_config_file, 'r', encoding='utf-8') as f:
                sites = yaml.safe_load(f) or {}
                
            sites[site_name] = config
            
            with open(self.sites_config_file, 'w', encoding='utf-8') as f:
                yaml.dump(sites, f, default_flow_style=False, allow_unicode=True)
                
        except Exception as e:
            print(f"添加网站配置失败: {e}")
            
    def update_site_config(self, site_name: str, config: Dict[str, Any]):
        """更新网站配置"""
        self.add_site_config(site_name, config)
        
    def remove_site_config(self, site_name: str):
        """删除网站配置"""
        try:
            with open(self.sites_config_file, 'r', encoding='utf-8') as f:
                sites = yaml.safe_load(f) or {}
                
            if site_name in sites:
                del sites[site_name]
                
                with open(self.sites_config_file, 'w', encoding='utf-8') as f:
                    yaml.dump(sites, f, default_flow_style=False, allow_unicode=True)
                    
        except Exception as e:
            print(f"删除网站配置失败: {e}")
            
    def get_system_config(self) -> Dict[str, Any]:
        """获取系统配置"""
        try:
            with open(self.system_config_file, 'r', encoding='utf-8') as f:
                return yaml.safe_load(f) or {}
        except Exception as e:
            print(f"读取系统配置失败: {e}")
            return {}
            
    def get_schedule_config(self) -> Dict[str, Any]:
        """获取定时任务配置"""
        system_config = self.get_system_config()
        return system_config.get('schedule', {
            "hour": "*/2",
            "minute": "0", 
            "second": "0"
        })
        
    def get_browser_config(self) -> Dict[str, Any]:
        """获取浏览器配置"""
        system_config = self.get_system_config()
        return system_config.get('browser', {
            "headless": True,
            "window_size": [1920, 1080],
            "user_agent": "",
            "timeout": 30,
            "implicit_wait": 10
        })
        
    def get_storage_config(self) -> Dict[str, Any]:
        """获取存储配置"""
        system_config = self.get_system_config()
        return system_config.get('storage', {
            "data_dir": "data",
            "max_items_per_site": 1000,
            "cleanup_days": 30
        })
        
    def update_system_config(self, config: Dict[str, Any]):
        """更新系统配置"""
        try:
            current_config = self.get_system_config()
            current_config.update(config)
            
            with open(self.system_config_file, 'w', encoding='utf-8') as f:
                yaml.dump(current_config, f, default_flow_style=False, allow_unicode=True)
                
        except Exception as e:
            print(f"更新系统配置失败: {e}")